/**
 * 设备运营信息
 */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import _ from 'lodash';
import { Button, Input, Card, Row, Col, Form, Switch, InputNumber, Select } from 'antd';
import AreaSelect from '../../components/areaSelect';
import { stringJoin } from '../../utils/util';

const Option = Select.Option;
const FormItem = Form.Item;

const styles = {
    rowStyle: {
        paddingTop: '15px'
    },
    input: {
        display: 'inline-block',
        width: '13em'
    },
    img: {
        width: '8em',
        height: '8em'
    },
    ip: {
        width: '80%',
        marginTop: '.6rem'
    },
    p: {
        marginTop: '5px',
        color: '#f04134',
        fontSize: '12px'
    }
};

class DetailOperationInfo extends Component {
    constructor(props, context) {
        super(props, context);
        this.state = {
            selectedLaunchArea: {},
            launchAreaName: '',
            launchAreaAddress: '',
            launchAreaContacts: '',
            launchAreaMobile: '',
        };
    }

    componentWillMount() {
        const { dispatch } = this.props;
        dispatch({
            type: 'deviceLaunchArea/query',
            payload: { size: 1000 }
        });
    }

    componentDidMount() {
        const { dispatch, device: { detailData } } = this.props;
        dispatch({
            type: 'serviceMode/query',
            payload: { size: 1000 }
        });
        this.setUpdateState(detailData);
        if (!!detailData) {
            // 设置安装用户信息
            const installUserData = {
                installUserName: detailData.installUserName || '',
                installUserAddress: detailData.installUserAddress || '',
                installUserMobile: detailData.installUserMobile || '',
                installUserProvince: detailData.installUserProvince || '',
                installUserCity: detailData.installUserCity || '',
                installUserArea: detailData.installUserArea || ''
            };
            const { dispatch } = this.props;
            dispatch({
                type: 'device/updateData',
                payload: installUserData
            });
            this.area.setValue([detailData.installUserProvince || '', detailData.installUserCity || '', detailData.installUserArea || '']);
            this.setUpdateState(detailData);
        }
    }

    componentWillReceiveProps(nextProps) {
        const { detailData } = nextProps.device;
        if (this.props.device.detailData !== detailData) {
            if (!!detailData) {
                // 设置安装用户信息
                const installUserData = {
                    installUserName: detailData.installUserName || '',
                    installUserAddress: detailData.installUserAddress || '',
                    installUserMobile: detailData.installUserMobile || '',
                    installUserProvince: detailData.installUserProvince || '',
                    installUserCity: detailData.installUserCity || '',
                    installUserArea: detailData.installUserArea || ''
                };
                const { dispatch } = this.props;
                dispatch({
                    type: 'device/updateData',
                    payload: installUserData
                });
                this.area.setValue([detailData.installUserProvince || '', detailData.installUserCity || '', detailData.installUserArea || '']);
                this.setUpdateState(detailData);
            }
        }
    }
    componentDidUpdate(prevProps, prevState) {
        if (this.state.a !== prevState.a) {
            const [installUserProvince, installUserCity, installUserArea] = this.area.getValue();
            const { dispatch } = this.props;
            dispatch({
                type: 'device/updateData',
                payload: { installUserProvince, installUserCity, installUserArea }
            });
        }
    }

    onChangeLaunchArea = (value) => {
        const { deviceLaunchArea: { list } } = this.props;
        const t = list.find(d => d.id === (value - 0));
        if (t) {
            this.setState({ launchAreaName: t.name });
        } else {
            this.setState({ launchAreaName: value });
            this.queryLaunchArea(value);
        }
    }

    onSelectLaunchArea = (value) => {
        const { deviceLaunchArea: { list } } = this.props;
        const d = list.find(t => t.id === (value - 0));
        if (d) {
            this.props.dispatch({
                type: 'device/setData',
                payload: {
                    launchAreaId: d.id,
                    launchAreaName: d.name
                }
            });
            this.setState({
                selectedLaunchArea: d,
                launchAreaName: d.name,
                launchAreaAddress: stringJoin([d.province, d.city, d.area, d.address]),
                launchAreaContacts: d.personInCharge,
                launchAreaMobile: d.mobile
            });
        }
    }

    setData = (key, v) => {
        const regular = /^1[3|4|5|7|8]\d{9}$/;

        if (key === 'installUserMobile') {
            v === '' ? this.setState({ showAlarm: false }) : this.setState({ showAlarm: !regular.test(v) });
        }
        const { dispatch } = this.props;
        dispatch({
            type: 'device/updateData',
            payload: { [key]: v }
        });
    }

    setUpdateState = (detailData) => {
        if (!detailData.mac) {
            this.setState({
                selectedLaunchArea: {},
                launchAreaList: [],
                launchAreaName: '',
                launchAreaAddress: '',
                launchAreaContacts: '',
                launchAreaMobile: ''
            });
            return;
        }

        if (detailData.launchArea) {
            this.setState({
                launchAreaName: detailData.launchArea.launchAreaName,
                launchAreaAddress: stringJoin([detailData.launchArea.province, detailData.launchArea.city, detailData.launchArea.area, detailData.launchArea.address]),
                launchAreaContacts: detailData.launchArea.personInCharge,
                launchAreaMobile: detailData.launchArea.mobile
            });
        }
    }

    parseServiceDetails = (arr, unit) => {
        if (!arr || !arr.length) return;
        let result = '';
        arr.forEach((obj) => {
            result += `${obj.num + unit + obj.price}元   `;
        });
        return result;
    }

    queryLaunchArea = _.debounce((value) => {
        const { dispatch } = this.props;
        dispatch({
            type: 'deviceLaunchArea/query',
            payload: {
                query: {
                    name: value || this.state.serviceName
                }
            }
        });
    }, 500)

    render() {
        const { launchAreaName } = this.state;
        const {
            deviceLaunchArea: { list: launchAreaList },
            device: { detailData = {}, tempDetail: { installUserName, installUserAddress, installUserMobile } }
        } = this.props;
        return (
            <div>
                <Form layout="vertical">
                    <Row gutter={16} style={styles.rowStyle}>
                        <Col span={6}>
                            <p>投放点名称：</p>
                            <Select
                                mode="combobox"
                                value={launchAreaName}
                                placeholder={'请选择投放点'}
                                notFoundContent="未找到匹配投放点"
                                style={styles.input}
                                defaultActiveFirstOption={false}
                                showArrow={false}
                                filterOption={false}
                                onChange={this.onChangeLaunchArea}
                                onSelect={this.onSelectLaunchArea}
                                disabled={!detailData.canModifyLaunchArea}
                            >
                                {launchAreaList.map(d => <Option key={d.id}>{d.name}</Option>)}
                            </Select>
                        </Col>
                        <Col span={6}>
                            <p>投放点地址：</p>
                            <p>{this.state.launchAreaAddress}</p>
                        </Col>
                        <Col span={6}>
                            <p>投放点负责人：</p>
                            <p>{this.state.launchAreaContacts}</p>
                        </Col>
                        <Col span={6}>
                            <p>负责人联系电话：</p>
                            <p>{this.state.launchAreaMobile}</p>
                        </Col>
                    </Row>
                    <Row gutter={16} style={styles.rowStyle}>
                        <Col span={6}>
                            <p>安装用户姓名：</p>
                            <Input value={installUserName} onChange={(v) => this.setData('installUserName', v.target.value)} placeholder="请输入安装用户姓名" style={styles.ip} />
                        </Col>
                        <Col span={6}>
                            <p>安装用户手机号：</p>
                            <Input value={installUserMobile} onChange={(v) => this.setData('installUserMobile', v.target.value)} placeholder="请输入安装用户手机号" style={styles.ip} />
                            {this.state.showAlarm ? <p style={styles.p}>请输入正确的手机号码</p> : null}
                        </Col>
                        <Col span={6}>
                            <p>安装用户所属行政区：</p>
                            <AreaSelect
                                ref={d => this.area = d}
                                onChange={() => this.setState({ a: Math.random() })}
                                style={styles.ip}
                                placeholder="请选择所属行政区"
                            />
                        </Col>
                        <Col span={6}>
                            <p>安装用户地址：</p>
                            <Input value={installUserAddress} onChange={(v) => this.setData('installUserAddress', v.target.value)} placeholder="请输入安装用户地址" style={styles.ip} />
                        </Col>
                    </Row>
                    <Row gutter={16} style={styles.rowStyle}>
                        {detailData.installFee &&
                            <Col span={6}>
                                <p>初装费：</p>
                                <p>&yen; {detailData.installFee}</p>
                            </Col>
                        }
                        <Col span={6}>
                            <p>设备二维码：</p>
                            {/* <img src={`/qrcode/${detailData.sno}.jpg`} style={styles.img} /> */}
                            {/* 兼容租赁和家用 */}
                            <img src={detailData.qrcodeUrl || `/qrcode/${detailData.sno}.jpg`} style={styles.img} />
                        </Col>
                    </Row>
                </Form>
            </div>
        );
    }
}

DetailOperationInfo.propTypes = {
};

export default connect(({ device, serviceMode, deviceLaunchArea }) => ({ device, serviceMode, deviceLaunchArea }))(DetailOperationInfo);
